<template>
  <view class="result-page">
    
    <view class="content">
      <view class="result-card">
        <view class="score-section" v-if="isGetScore">
          <view class="score-circle">
            <text class="score-value">{{ resultScore }}</text>
          </view>
          <text class="score-desc">{{ getScoreDesc(resultScore) }}</text>
        </view>
        
        <view class="result-section">
          <view class="section-title">
            <text class="title-text">面试结果分析</text>
          </view>
          
          <view class="analysis-content">
            <!-- <text v-if="!showFullText" ref="resultText" class="analysis-text">{{ displayText }}</text> -->
            <text class="analysis-text">{{ resultData }}</text>
          </view>
        </view>
        
        <view class="action-buttons" v-if="isOver">
          <button class="action-btn" @click="goToHistory">历史面试</button>
          <button class="action-btn primary" @click="goResume">简历列表</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed, onUnmounted, nextTick } from 'vue'
import { getInterviewResult, getInterviewDetail } from '@/api/interview'
import env from '@/env'
import { useAuthStore } from '@/store/index';
import { useWebSocket } from '@/utils/useWebSocket'
import { mockInterviewWebSocketProcess } from '@/api/ai'

const authStore = useAuthStore();
const statusBarHeight = ref(20)
const interviewId = ref('')
const resumeId = ref('')
const loading = ref(true)
const textIndex = ref(0)
const showFullText = ref(false)
const resultText = ref(null)
const typingInterval = ref(null)
const isOver = ref(false)
const isGetScore = ref(false)
const { messages, isConnected, connect, sendMessage, close, onMessage } = useWebSocket(env.websocket)
const receivedResponseFlag = ref(false)
const timeoutTimer = ref(null)

// 模拟面试结果数据
const interviewResult = ref({
  id: 'mock-id',
  score: 85,
  analysis: '面试整体表现良好，展示了扎实的专业知识和良好的沟通能力。\n\n优势：\n1. 专业知识扎实，能够清晰表达技术概念\n2. 结构化思维清晰，答题逻辑性强\n3. 举例说明具体且有说服力\n4. 语言表达流畅，沟通能力良好\n\n改进空间：\n1. 部分问题回答深度不足，可以进一步展开细节\n2. 对公司业务了解不够充分\n3. 职业规划部分可以更具体，与岗位结合更紧密\n\n建议：\n- 深入了解目标公司的业务和技术栈\n- 准备更多具体的项目案例，包括遇到的挑战和解决方案\n- 在回答问题时，可以多使用STAR法则(情景-任务-行动-结果)来组织答案'
})

// 计算当前应该显示的文本
const displayText = computed(() => {
  return interviewResult.value.analysis.substring(0, textIndex.value)
})

const resultData = ref('')
const resultScore = ref(null)

// 根据得分返回评价描述
const getScoreDesc = (score) => {
  if (score >= 90) return '优秀'
  if (score >= 80) return '良好'
  if (score >= 70) return '一般'
  if (score >= 60) return '及格'
  return '需要提升'
}

// 注册WebSocket消息处理函数
onMessage((data) => {
  try {
    if (typeof data === 'string') {
      try {
        const parsedData = JSON.parse(data);
        if (parsedData.topic === 'EVALUATE_ANSWER') {
          receivedResponseFlag.value = true;
          
          if (parsedData.content === '[DONE]' || parsedData.content.includes('[DONE]')) {
            console.log('WebSocket结果接收完成');
            isOver.value = true;
            getSocre(interviewId.value);
            loading.value = false;
            return;
          }
          
          resultData.value += parsedData.content;
          return;
        }
      } catch (e) {
        // 如果不是JSON格式，直接处理字符串
        if (data === '[DONE]' || data.includes('[DONE]')) {
          console.log('WebSocket结果接收完成');
          isOver.value = true;
          getSocre(interviewId.value);
          loading.value = false;
          return;
        }
        resultData.value += data;
        receivedResponseFlag.value = true;
      }
    }
  } catch (error) {
    console.error('处理WebSocket消息出错:', error);
  }
});

// 获取面试结果
const fetchInterviewResult = async (id) => {
  try {
    loading.value = true;
    resultData.value = '';
    receivedResponseFlag.value = false;
    
    // 检查WebSocket连接状态
    if (!isConnected.value) {
      console.log('WebSocket未连接，尝试连接...');
      await connect();
      console.log('WebSocket连接已建立');
    } else {
      console.log('WebSocket已连接，状态正常');
    }
    
    // 发送请求数据到后端，触发WebSocket消息推送
    const requestData = {
      type: 'EVALUATE_ANSWER',
      interviewEvaluationBo: {
        interviewId: id,
        resumeId: resumeId.value
      }
    };
    
    // 使用mockInterviewWebSocketProcess接口
    mockInterviewWebSocketProcess(requestData).then(res => {
      console.log('触发WebSocket消息推送成功:', res);
      
      // 设置超时机制，如果10秒内未收到WebSocket消息，则使用传统HTTP请求
      timeoutTimer.value = setTimeout(async () => {
        if (!receivedResponseFlag.value) {
          console.log('WebSocket消息接收超时，使用传统HTTP请求');
        }
      }, 10000);
    }).catch(err => {
      console.error('触发WebSocket消息推送失败:', err);
      // 出错时使用传统HTTP请求作为回退
    });
    
    return true;
  } catch (error) {
    console.error('获取面试结果失败:', error);
    loading.value = false;
    return false;
  }
};

const getSocre = async (id) => {
  try {
    const res = await getInterviewDetail(id)
    if (res.code === 200) {
      isGetScore.value = true
      resultScore.value = res.data.score
    } else {
      uni.showToast({
        title: '获取分数失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('获取分数失败:', error)
  }
}

// 文字逐步显示效果
const startTypingEffect = () => {
  const fullText = resultData.value
  const totalLength = fullText.length
  
  // 每40ms显示一个字符
  typingInterval.value = setInterval(() => {
    if (textIndex.value < totalLength) {
      textIndex.value += 1
    } else {
      clearInterval(typingInterval.value)
      showFullText.value = true
    }
  }, 40)
}

// 跳转到历史面试页面
const goToHistory = () => {
  uni.reLaunch({
    url: '/pages/interview/index?type=history'
  })
}

// 返回首页
const goResume = () => {
  uni.reLaunch({
    url: '/pages/interview/index?type=resumeList'
  })
}

onMounted(async() => {
  // 获取状态栏高度
  const systemInfo = uni.getSystemInfoSync()
  statusBarHeight.value = systemInfo.statusBarHeight
  
  // 获取页面参数
  const pages = getCurrentPages()
  const page = pages[pages.length - 1]
  
  try {
    // 启动时先尝试连接WebSocket
    try {
      connect().then(() => {
        console.log('WebSocket连接成功，可以接收消息');
      }).catch(err => {
        console.error('WebSocket连接失败:', err);
      });
    } catch (e) {
      console.error('连接WebSocket异常:', e);
    }
    
    if (page.options && page.options.id && page.options.resumeId) {
      interviewId.value = page.options.id
      resumeId.value = page.options.resumeId
      // 优先使用WebSocket获取结果
      const wsResult = await fetchInterviewResult(interviewId.value)
      // 不需要等待WebSocket结果，如果超时会自动降级到HTTP请求
    } else {
      // 没有ID参数，使用模拟数据
      resultData.value = interviewResult.value.analysis;
      isOver.value = true;
      isGetScore.value = true;
      resultScore.value = interviewResult.value.score;
      loading.value = false;
    }
  } catch (error) {
    console.error('初始化面试结果页面失败:', error)
    uni.showToast({
      title: '加载失败，请重试',
      icon: 'none'
    })
  }
})

// 组件销毁时清除定时器和WebSocket连接
onUnmounted(() => {
  if (typingInterval.value) {
    clearInterval(typingInterval.value)
  }
  
  if (timeoutTimer.value) {
    clearTimeout(timeoutTimer.value);
  }
  
  // 关闭WebSocket连接
  close();
})
</script>

<style lang="scss" scoped>
.result-page {
  min-height: 100vh;
  background-color: #f5f7fb;
  
  .content {
    padding: 30rpx;
  }
  
  .result-card {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 40rpx 30rpx;
    box-shadow: 0 2rpx 20rpx rgba(0, 0, 0, 0.1);
  }
  
  .score-section {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 40rpx;
    
    .score-circle {
      width: 200rpx;
      height: 200rpx;
      border-radius: 50%;
      background: linear-gradient(135deg, #5ac725, #3ca917);
      display: flex;
      justify-content: center;
      align-items: center;
      margin-bottom: 20rpx;
      box-shadow: 0 4rpx 20rpx rgba(90, 199, 37, 0.3);
      
      .score-value {
        color: #fff;
        font-size: 60rpx;
        font-weight: bold;
      }
    }
    
    .score-desc {
      font-size: 32rpx;
      color: #333;
      font-weight: 500;
    }
  }
  
  .result-section {
    margin-bottom: 40rpx;
    
    .section-title {
      margin-bottom: 20rpx;
      
      .title-text {
        font-size: 32rpx;
        font-weight: 500;
        color: #333;
        position: relative;
        padding-left: 24rpx;
        
        &::before {
          content: '';
          position: absolute;
          left: 0;
          top: 50%;
          transform: translateY(-50%);
          width: 8rpx;
          height: 32rpx;
          background-color: #5ac725;
          border-radius: 4rpx;
        }
      }
    }
    
    .analysis-content {
      padding: 20rpx;
      background-color: #f9f9f9;
      border-radius: 12rpx;
      
      .analysis-text {
        font-size: 28rpx;
        color: #333;
        line-height: 1.6;
        white-space: pre-wrap;
      }
    }
  }
  
  .action-buttons {
    display: flex;
    justify-content: space-between;
    
    .action-btn {
      flex: 1;
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      border-radius: 40rpx;
      font-size: 28rpx;
      margin: 0 15rpx;
      
      &:first-child {
        margin-left: 0;
      }
      
      &:last-child {
        margin-right: 0;
      }
      
      &.primary {
        background-color: #5ac725;
        color: #fff;
      }
      
      &:not(.primary) {
        background-color: #f0f0f0;
        color: #666;
      }
    }
  }
}
</style> 